home *** CD-ROM | disk | FTP | other *** search
/ Aminet 32 / Aminet 32 (1999)(Schatztruhe)[!][Aug 1999].iso / Aminet / dev / lang / Python151_Src.lha / Python1.5_Source / Objects / dictobject.c < prev    next >
C/C++ Source or Header  |  1998-05-30  |  25KB  |  1,113 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Dictionaru object implementation using a hash table */
  33.  
  34. #include "Python.h"
  35.  
  36.  
  37. /*
  38.  * MINSIZE is the minimum size of a dictionary.
  39.  */
  40.  
  41. #define MINSIZE 4
  42.  
  43. /*
  44. Table of irreducible polynomials to efficiently cycle through
  45. GF(2^n)-{0}, 2<=n<=30.
  46. */
  47. static long polys[] = {
  48.     4 + 3,
  49.     8 + 3,
  50.     16 + 3,
  51.     32 + 5,
  52.     64 + 3,
  53.     128 + 3,
  54.     256 + 29,
  55.     512 + 17,
  56.     1024 + 9,
  57.     2048 + 5,
  58.     4096 + 83,
  59.     8192 + 27,
  60.     16384 + 43,
  61.     32768 + 3,
  62.     65536 + 45,
  63.     131072 + 9,
  64.     262144 + 39,
  65.     524288 + 39,
  66.     1048576 + 9,
  67.     2097152 + 5,
  68.     4194304 + 3,
  69.     8388608 + 33,
  70.     16777216 + 27,
  71.     33554432 + 9,
  72.     67108864 + 71,
  73.     134217728 + 39,
  74.     268435456 + 9,
  75.     536870912 + 5,
  76.     1073741824 + 83,
  77.     0
  78. };
  79.  
  80. /* Object used as dummy key to fill deleted entries */
  81. static PyObject *dummy; /* Initialized by first call to newdictobject() */
  82.  
  83. /*
  84. Invariant for entries: when in use, de_value is not NULL and de_key is
  85. not NULL and not dummy; when not in use, de_value is NULL and de_key
  86. is either NULL or dummy.  A dummy key value cannot be replaced by
  87. NULL, since otherwise other keys may be lost.
  88. */
  89. typedef struct {
  90.     long me_hash;
  91.     PyObject *me_key;
  92.     PyObject *me_value;
  93. #ifdef USE_CACHE_ALIGNED
  94.     long    aligner;
  95. #endif
  96. } dictentry;
  97.  
  98. /*
  99. To ensure the lookup algorithm terminates, the table size must be a
  100. prime number and there must be at least one NULL key in the table.
  101. The value ma_fill is the number of non-NULL keys; ma_used is the number
  102. of non-NULL, non-dummy keys.
  103. To avoid slowing down lookups on a near-full table, we resize the table
  104. when it is more than half filled.
  105. */
  106. typedef struct {
  107.     PyObject_HEAD
  108.     int ma_fill;
  109.     int ma_used;
  110.     int ma_size;
  111.     int ma_poly;
  112.     dictentry *ma_table;
  113. } dictobject;
  114.  
  115. #include "protos/dictobject_protos.h"
  116.  
  117. PyObject *
  118. PyDict_New()
  119. {
  120.     register dictobject *mp;
  121.     if (dummy == NULL) { /* Auto-initialize dummy */
  122.         dummy = PyString_FromString("<dummy key>");
  123.         if (dummy == NULL)
  124.             return NULL;
  125.     }
  126.     mp = PyObject_NEW(dictobject, &PyDict_Type);
  127.     if (mp == NULL)
  128.         return NULL;
  129.     mp->ma_size = 0;
  130.     mp->ma_poly = 0;
  131.     mp->ma_table = NULL;
  132.     mp->ma_fill = 0;
  133.     mp->ma_used = 0;
  134.     return (PyObject *)mp;
  135. }
  136.  
  137. /*
  138. The basic lookup function used by all operations.
  139. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
  140. Open addressing is preferred over chaining since the link overhead for
  141. chaining would be substantial (100% with typical malloc overhead).
  142. However, instead of going through the table at constant steps, we cycle
  143. through the values of GF(2^n)-{0}. This avoids modulo computations, being
  144. much cheaper on RISC machines, without leading to clustering.
  145.  
  146. First a 32-bit hash value, 'sum', is computed from the key string.
  147. The first character is added an extra time shifted by 8 to avoid hashing
  148. single-character keys (often heavily used variables) too close together.
  149. All arithmetic on sum should ignore overflow.
  150.  
  151. The initial probe index is then computed as sum mod the table size.
  152. Subsequent probe indices use the values of x^i in GF(2^n) as an offset,
  153. where x is a root. The initial value is derived from sum, too.
  154.  
  155. (This version is due to Reimer Behrends, some ideas are also due to
  156. Jyrki Alakuijala and Vladimir Marangozov.)
  157. */
  158. static dictentry *lookdict Py_PROTO((dictobject *, PyObject *, long));
  159. static dictentry *
  160. lookdict(mp, key, hash)
  161.     dictobject *mp;
  162.     PyObject *key;
  163.     register long hash;
  164. {
  165.     register int i;
  166.     register unsigned incr;
  167.     register dictentry *freeslot;
  168.     register unsigned int mask = mp->ma_size-1;
  169.     dictentry *ep0 = mp->ma_table;
  170.     register dictentry *ep;
  171.     /* We must come up with (i, incr) such that 0 <= i < ma_size
  172.        and 0 < incr < ma_size and both are a function of hash */
  173.     i = (~hash) & mask;
  174.     /* We use ~hash instead of hash, as degenerate hash functions, such
  175.        as for ints <sigh>, can have lots of leading zeros. It's not
  176.        really a performance risk, but better safe than sorry. */
  177.     ep = &ep0[i];
  178.     if (ep->me_key == NULL)
  179.         return ep;
  180.     if (ep->me_key == dummy)
  181.         freeslot = ep;
  182.     else {
  183.         if (ep->me_key == key ||
  184.          (ep->me_hash == hash &&
  185.           PyObject_Compare(ep->me_key, key) == 0))
  186.         {
  187.             return ep;
  188.         }
  189.         freeslot = NULL;
  190.     }
  191.     /* XXX What if PyObject_Compare returned an exception? */
  192.     /* Derive incr from sum, just to make it more arbitrary. Note that
  193.        incr must not be 0, or we will get into an infinite loop.*/
  194.     incr = (hash ^ ((unsigned long)hash >> 3)) & mask;
  195.     if (!incr)
  196.         incr = mask;
  197.     else if (incr > mask) /* Cycle through GF(2^n)-{0} */
  198.         incr ^= mp->ma_poly; /* This will implicitly clear the
  199.                     highest bit */
  200.     for (;;) {
  201.         ep = &ep0[(i+incr)&mask];
  202.         if (ep->me_key == NULL) {
  203.             if (freeslot != NULL)
  204.                 return freeslot;
  205.             else
  206.                 return ep;
  207.         }
  208.         if (ep->me_key == dummy) {
  209.             if (freeslot == NULL)
  210.                 freeslot = ep;
  211.         }
  212.         else if (ep->me_key == key ||
  213.              (ep->me_hash == hash &&
  214.               PyObject_Compare(ep->me_key, key) == 0)) {
  215.             return ep;
  216.         }
  217.         /* XXX What if PyObject_Compare returned an exception? */
  218.         /* Cycle through GF(2^n)-{0} */
  219.         incr = incr << 1;
  220.         if (incr > mask)
  221.             incr ^= mp->ma_poly;
  222.     }
  223. }
  224.  
  225. /*
  226. Internal routine to insert a new item into the table.
  227. Used both by the internal resize routine and by the public insert routine.
  228. Eats a reference to key and one to value.
  229. */
  230. static void insertdict
  231.     Py_PROTO((dictobject *, PyObject *, long, PyObject *));
  232. static void
  233. insertdict(mp, key, hash, value)
  234.     register dictobject *mp;
  235.     PyObject *key;
  236.     long hash;
  237.     PyObject *value;
  238. {
  239.     PyObject *old_value;
  240.     register dictentry *ep;
  241.     ep = lookdict(mp, key, hash);
  242.     if (ep->me_value != NULL) {
  243.         old_value = ep->me_value;
  244.         ep->me_value = value;
  245.         Py_DECREF(old_value); /* which **CAN** re-enter */
  246.         Py_DECREF(key);
  247.     }
  248.     else {
  249.         if (ep->me_key == NULL)
  250.             mp->ma_fill++;
  251.         else
  252.             Py_DECREF(ep->me_key);
  253.         ep->me_key = key;
  254.         ep->me_hash = hash;
  255.         ep->me_value = value;
  256.         mp->ma_used++;
  257.     }
  258. }
  259.  
  260. /*
  261. Restructure the table by allocating a new table and reinserting all
  262. items again.  When entries have been deleted, the new table may
  263. actually be smaller than the old one.
  264. */
  265. static int dictresize Py_PROTO((dictobject *, int));
  266. static int
  267. dictresize(mp, minused)
  268.     dictobject *mp;
  269.     int minused;
  270. {
  271.     register int oldsize = mp->ma_size;
  272.     register int newsize, newpoly;
  273.     register dictentry *oldtable = mp->ma_table;
  274.     register dictentry *newtable;
  275.     register dictentry *ep;
  276.     register int i;
  277.     for (i = 0, newsize = MINSIZE; ; i++, newsize <<= 1) {
  278.         if (i > sizeof(polys)/sizeof(polys[0])) {
  279.             /* Ran out of polynomials */
  280.             PyErr_NoMemory();
  281.             return -1;
  282.         }
  283.         if (newsize > minused) {
  284.             newpoly = polys[i];
  285.             break;
  286.         }
  287.     }
  288.     newtable = (dictentry *) calloc(sizeof(dictentry), newsize);
  289.     if (newtable == NULL) {
  290.         PyErr_NoMemory();
  291.         return -1;
  292.     }
  293.     mp->ma_size = newsize;
  294.     mp->ma_poly = newpoly;
  295.     mp->ma_table = newtable;
  296.     mp->ma_fill = 0;
  297.     mp->ma_used = 0;
  298.  
  299.     /* Make two passes, so we can avoid decrefs
  300.        (and possible side effects) till the table is copied */
  301.     for (i = 0, ep = oldtable; i < oldsize; i++, ep++) {
  302.         if (ep->me_value != NULL)
  303.             insertdict(mp,ep->me_key,ep->me_hash,ep->me_value);
  304.     }
  305.     for (i = 0, ep = oldtable; i < oldsize; i++, ep++) {
  306.         if (ep->me_value == NULL) {
  307.             Py_XDECREF(ep->me_key);
  308.         }
  309.     }
  310.  
  311.     PyMem_XDEL(oldtable);
  312.     return 0;
  313. }
  314.  
  315. PyObject *
  316. PyDict_GetItem(op, key)
  317.     PyObject *op;
  318.     PyObject *key;
  319. {
  320.     long hash;
  321.     if (!PyDict_Check(op)) {
  322.         PyErr_BadInternalCall();
  323.         return NULL;
  324.     }
  325.     if (((dictobject *)op)->ma_table == NULL)
  326.         return NULL;
  327. #ifdef CACHE_HASH
  328.     if (!PyString_Check(key) ||
  329.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  330. #endif
  331.     {
  332.         hash = PyObject_Hash(key);
  333.         if (hash == -1)
  334.             return NULL;
  335.     }
  336.     return lookdict((dictobject *)op, key, hash) -> me_value;
  337. }
  338.  
  339. int
  340. PyDict_SetItem(op, key, value)
  341.     register PyObject *op;
  342.     PyObject *key;
  343.     PyObject *value;
  344. {
  345.     register dictobject *mp;
  346.     register long hash;
  347.     if (!PyDict_Check(op)) {
  348.         PyErr_BadInternalCall();
  349.         return -1;
  350.     }
  351.     mp = (dictobject *)op;
  352. #ifdef CACHE_HASH
  353.     if (PyString_Check(key)) {
  354. #ifdef INTERN_STRINGS
  355.         if (((PyStringObject *)key)->ob_sinterned != NULL) {
  356.             key = ((PyStringObject *)key)->ob_sinterned;
  357.             hash = ((PyStringObject *)key)->ob_shash;
  358.         }
  359.         else
  360. #endif
  361.         {
  362.             hash = ((PyStringObject *)key)->ob_shash;
  363.             if (hash == -1)
  364.                 hash = PyObject_Hash(key);
  365.         }
  366.     }
  367.     else
  368. #endif
  369.     {
  370.         hash = PyObject_Hash(key);
  371.         if (hash == -1)
  372.             return -1;
  373.     }
  374.     /* if fill >= 2/3 size, double in size */
  375.     if (mp->ma_fill*3 >= mp->ma_size*2) {
  376.         if (dictresize(mp, mp->ma_used*2) != 0) {
  377.             if (mp->ma_fill+1 > mp->ma_size)
  378.                 return -1;
  379.         }
  380.     }
  381.     Py_INCREF(value);
  382.     Py_INCREF(key);
  383.     insertdict(mp, key, hash, value);
  384.     return 0;
  385. }
  386.  
  387. int
  388. PyDict_DelItem(op, key)
  389.     PyObject *op;
  390.     PyObject *key;
  391. {
  392.     register dictobject *mp;
  393.     register long hash;
  394.     register dictentry *ep;
  395.     PyObject *old_value, *old_key;
  396.  
  397.     if (!PyDict_Check(op)) {
  398.         PyErr_BadInternalCall();
  399.         return -1;
  400.     }
  401. #ifdef CACHE_HASH
  402.     if (!PyString_Check(key) ||
  403.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  404. #endif
  405.     {
  406.         hash = PyObject_Hash(key);
  407.         if (hash == -1)
  408.             return -1;
  409.     }
  410.     mp = (dictobject *)op;
  411.     if (((dictobject *)op)->ma_table == NULL)
  412.         goto empty;
  413.     ep = lookdict(mp, key, hash);
  414.     if (ep->me_value == NULL) {
  415.     empty:
  416.         PyErr_SetObject(PyExc_KeyError, key);
  417.         return -1;
  418.     }
  419.     old_key = ep->me_key;
  420.     Py_INCREF(dummy);
  421.     ep->me_key = dummy;
  422.     old_value = ep->me_value;
  423.     ep->me_value = NULL;
  424.     mp->ma_used--;
  425.     Py_DECREF(old_value); 
  426.     Py_DECREF(old_key); 
  427.     return 0;
  428. }
  429.  
  430. void
  431. PyDict_Clear(op)
  432.     PyObject *op;
  433. {
  434.     int i, n;
  435.     register dictentry *table;
  436.     dictobject *mp;
  437.     if (!PyDict_Check(op))
  438.         return;
  439.     mp = (dictobject *)op;
  440.     table = mp->ma_table;
  441.     if (table == NULL)
  442.         return;
  443.     n = mp->ma_size;
  444.     mp->ma_size = mp->ma_used = mp->ma_fill = 0;
  445.     mp->ma_table = NULL;
  446.     for (i = 0; i < n; i++) {
  447.         Py_XDECREF(table[i].me_key);
  448.         Py_XDECREF(table[i].me_value);
  449.     }
  450.     PyMem_DEL(table);
  451. }
  452.  
  453. int
  454. PyDict_Next(op, ppos, pkey, pvalue)
  455.     PyObject *op;
  456.     int *ppos;
  457.     PyObject **pkey;
  458.     PyObject **pvalue;
  459. {
  460.     int i;
  461.     register dictobject *mp;
  462.     if (!PyDict_Check(op))
  463.         return 0;
  464.     mp = (dictobject *)op;
  465.     i = *ppos;
  466.     if (i < 0)
  467.         return 0;
  468.     while (i < mp->ma_size && mp->ma_table[i].me_value == NULL)
  469.         i++;
  470.     *ppos = i+1;
  471.     if (i >= mp->ma_size)
  472.         return 0;
  473.     if (pkey)
  474.         *pkey = mp->ma_table[i].me_key;
  475.     if (pvalue)
  476.         *pvalue = mp->ma_table[i].me_value;
  477.     return 1;
  478. }
  479.  
  480. /* Methods */
  481.  
  482. static void
  483. dict_dealloc(mp)
  484.     register dictobject *mp;
  485. {
  486.     register int i;
  487.     register dictentry *ep;
  488.     for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) {
  489.         if (ep->me_key != NULL) {
  490.             Py_DECREF(ep->me_key);
  491.         }
  492.         if (ep->me_value != NULL) {
  493.             Py_DECREF(ep->me_value);
  494.         }
  495.     }
  496.     PyMem_XDEL(mp->ma_table);
  497.     PyMem_DEL(mp);
  498. }
  499.  
  500. static int
  501. dict_print(mp, fp, flags)
  502.     register dictobject *mp;
  503.     register FILE *fp;
  504.     register int flags;
  505. {
  506.     register int i;
  507.     register int any;
  508.     register dictentry *ep;
  509.  
  510.     i = Py_ReprEnter((PyObject*)mp);
  511.     if (i != 0) {
  512.         if (i < 0)
  513.             return i;
  514.         fprintf(fp, "{...}");
  515.         return 0;
  516.     }
  517.  
  518.     fprintf(fp, "{");
  519.     any = 0;
  520.     for (i = 0, ep = mp->ma_table; i < mp->ma_size; i++, ep++) {
  521.         if (ep->me_value != NULL) {
  522.             if (any++ > 0)
  523.                 fprintf(fp, ", ");
  524.             if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
  525.                 Py_ReprLeave((PyObject*)mp);
  526.                 return -1;
  527.             }
  528.             fprintf(fp, ": ");
  529.             if (PyObject_Print(ep->me_value, fp, 0) != 0) {
  530.                 Py_ReprLeave((PyObject*)mp);
  531.                 return -1;
  532.             }
  533.         }
  534.     }
  535.     fprintf(fp, "}");
  536.     Py_ReprLeave((PyObject*)mp);
  537.     return 0;
  538. }
  539.  
  540. static PyObject *
  541. dict_repr(mp)
  542.     dictobject *mp;
  543. {
  544.     auto PyObject *v;
  545.     PyObject *sepa, *colon;
  546.     register int i;
  547.     register int any;
  548.     register dictentry *ep;
  549.  
  550.     i = Py_ReprEnter((PyObject*)mp);
  551.     if (i != 0) {
  552.         if (i > 0)
  553.             return PyString_FromString("{...}");
  554.         return NULL;
  555.     }
  556.  
  557.     v = PyString_FromString("{");
  558.     sepa = PyString_FromString(", ");
  559.     colon = PyString_FromString(": ");
  560.     any = 0;
  561.     for (i = 0, ep = mp->ma_table; i < mp->ma_size && v; i++, ep++) {
  562.         if (ep->me_value != NULL) {
  563.             if (any++)
  564.                 PyString_Concat(&v, sepa);
  565.             PyString_ConcatAndDel(&v, PyObject_Repr(ep->me_key));
  566.             PyString_Concat(&v, colon);
  567.             PyString_ConcatAndDel(&v, PyObject_Repr(ep->me_value));
  568.         }
  569.     }
  570.     PyString_ConcatAndDel(&v, PyString_FromString("}"));
  571.     Py_ReprLeave((PyObject*)mp);
  572.     Py_XDECREF(sepa);
  573.     Py_XDECREF(colon);
  574.     return v;
  575. }
  576.  
  577. static int
  578. dict_length(mp)
  579.     dictobject *mp;
  580. {
  581.     return mp->ma_used;
  582. }
  583.  
  584. static PyObject *
  585. dict_subscript(mp, key)
  586.     dictobject *mp;
  587.     register PyObject *key;
  588. {
  589.     PyObject *v;
  590.     long hash;
  591.     if (mp->ma_table == NULL) {
  592.         PyErr_SetObject(PyExc_KeyError, key);
  593.         return NULL;
  594.     }
  595. #ifdef CACHE_HASH
  596.     if (!PyString_Check(key) ||
  597.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  598. #endif
  599.     {
  600.         hash = PyObject_Hash(key);
  601.         if (hash == -1)
  602.             return NULL;
  603.     }
  604.     v = lookdict(mp, key, hash) -> me_value;
  605.     if (v == NULL)
  606.         PyErr_SetObject(PyExc_KeyError, key);
  607.     else
  608.         Py_INCREF(v);
  609.     return v;
  610. }
  611.  
  612. static int
  613. dict_ass_sub(mp, v, w)
  614.     dictobject *mp;
  615.     PyObject *v, *w;
  616. {
  617.     if (w == NULL)
  618.         return PyDict_DelItem((PyObject *)mp, v);
  619.     else
  620.         return PyDict_SetItem((PyObject *)mp, v, w);
  621. }
  622.  
  623. static PyMappingMethods dict_as_mapping = {
  624.     (inquiry)dict_length, /*mp_length*/
  625.     (binaryfunc)dict_subscript, /*mp_subscript*/
  626.     (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
  627. };
  628.  
  629. static PyObject *
  630. dict_keys(mp, args)
  631.     register dictobject *mp;
  632.     PyObject *args;
  633. {
  634.     register PyObject *v;
  635.     register int i, j;
  636.     if (!PyArg_NoArgs(args))
  637.         return NULL;
  638.     v = PyList_New(mp->ma_used);
  639.     if (v == NULL)
  640.         return NULL;
  641.     for (i = 0, j = 0; i < mp->ma_size; i++) {
  642.         if (mp->ma_table[i].me_value != NULL) {
  643.             PyObject *key = mp->ma_table[i].me_key;
  644.             Py_INCREF(key);
  645.             PyList_SetItem(v, j, key);
  646.             j++;
  647.         }
  648.     }
  649.     return v;
  650. }
  651.  
  652. static PyObject *
  653. dict_values(mp, args)
  654.     register dictobject *mp;
  655.     PyObject *args;
  656. {
  657.     register PyObject *v;
  658.     register int i, j;
  659.     if (!PyArg_NoArgs(args))
  660.         return NULL;
  661.     v = PyList_New(mp->ma_used);
  662.     if (v == NULL)
  663.         return NULL;
  664.     for (i = 0, j = 0; i < mp->ma_size; i++) {
  665.         if (mp->ma_table[i].me_value != NULL) {
  666.             PyObject *value = mp->ma_table[i].me_value;
  667.             Py_INCREF(value);
  668.             PyList_SetItem(v, j, value);
  669.             j++;
  670.         }
  671.     }
  672.     return v;
  673. }
  674.  
  675. static PyObject *
  676. dict_items(mp, args)
  677.     register dictobject *mp;
  678.     PyObject *args;
  679. {
  680.     register PyObject *v;
  681.     register int i, j;
  682.     if (!PyArg_NoArgs(args))
  683.         return NULL;
  684.     v = PyList_New(mp->ma_used);
  685.     if (v == NULL)
  686.         return NULL;
  687.     for (i = 0, j = 0; i < mp->ma_size; i++) {
  688.         if (mp->ma_table[i].me_value != NULL) {
  689.             PyObject *key = mp->ma_table[i].me_key;
  690.             PyObject *value = mp->ma_table[i].me_value;
  691.             PyObject *item = PyTuple_New(2);
  692.             if (item == NULL) {
  693.                 Py_DECREF(v);
  694.                 return NULL;
  695.             }
  696.             Py_INCREF(key);
  697.             PyTuple_SetItem(item, 0, key);
  698.             Py_INCREF(value);
  699.             PyTuple_SetItem(item, 1, value);
  700.             PyList_SetItem(v, j, item);
  701.             j++;
  702.         }
  703.     }
  704.     return v;
  705. }
  706.  
  707. static PyObject *
  708. dict_update(mp, args)
  709.       register dictobject *mp;
  710.       PyObject *args;
  711. {
  712.     register int i;
  713.     dictobject *other;
  714.         dictentry *entry;
  715.     if (!PyArg_Parse(args, "O!", &PyDict_Type, &other))
  716.         return NULL;
  717.     if (other == mp)
  718.         goto done; /* a.update(a); nothing to do */
  719.     /* Do one big resize at the start, rather than incrementally
  720.        resizing as we insert new items.  Expect that there will be
  721.        no (or few) overlapping keys. */
  722.     if ((mp->ma_fill + other->ma_used)*3 >= mp->ma_size*2) {
  723.         if (dictresize(mp, (mp->ma_used + other->ma_used)*3/2) != 0)
  724.             return NULL;
  725.     }
  726.     for (i = 0; i < other->ma_size; i++) {
  727.         entry = &other->ma_table[i];
  728.         if (entry->me_value != NULL) {
  729.             Py_INCREF(entry->me_key);
  730.             Py_INCREF(entry->me_value);
  731.             insertdict(mp, entry->me_key, entry->me_hash,
  732.                    entry->me_value);
  733.         }
  734.     }
  735.   done:
  736.     Py_INCREF(Py_None);
  737.     return Py_None;
  738. }
  739.  
  740. static PyObject *
  741. dict_copy(mp, args)
  742.       register dictobject *mp;
  743.       PyObject *args;
  744. {
  745.     register int i;
  746.     dictobject *copy;
  747.         dictentry *entry;
  748.     if (!PyArg_Parse(args, ""))
  749.         return NULL;
  750.     copy = (dictobject *)PyDict_New();
  751.     if (copy == NULL)
  752.         return NULL;
  753.     if (mp->ma_used > 0) {
  754.         if (dictresize(copy, mp->ma_used*3/2) != 0)
  755.             return NULL;
  756.         for (i = 0; i < mp->ma_size; i++) {
  757.             entry = &mp->ma_table[i];
  758.             if (entry->me_value != NULL) {
  759.                 Py_INCREF(entry->me_key);
  760.                 Py_INCREF(entry->me_value);
  761.                 insertdict(copy, entry->me_key, entry->me_hash,
  762.                        entry->me_value);
  763.             }
  764.         }
  765.     }
  766.     return (PyObject *)copy;
  767. }
  768.  
  769. int
  770. PyDict_Size(mp)
  771.     PyObject *mp;
  772. {
  773.     if (mp == NULL || !PyDict_Check(mp)) {
  774.         PyErr_BadInternalCall();
  775.         return 0;
  776.     }
  777.     return ((dictobject *)mp)->ma_used;
  778. }
  779.  
  780. PyObject *
  781. PyDict_Keys(mp)
  782.     PyObject *mp;
  783. {
  784.     if (mp == NULL || !PyDict_Check(mp)) {
  785.         PyErr_BadInternalCall();
  786.         return NULL;
  787.     }
  788.     return dict_keys((dictobject *)mp, (PyObject *)NULL);
  789. }
  790.  
  791. PyObject *
  792. PyDict_Values(mp)
  793.     PyObject *mp;
  794. {
  795.     if (mp == NULL || !PyDict_Check(mp)) {
  796.         PyErr_BadInternalCall();
  797.         return NULL;
  798.     }
  799.     return dict_values((dictobject *)mp, (PyObject *)NULL);
  800. }
  801.  
  802. PyObject *
  803. PyDict_Items(mp)
  804.     PyObject *mp;
  805. {
  806.     if (mp == NULL || !PyDict_Check(mp)) {
  807.         PyErr_BadInternalCall();
  808.         return NULL;
  809.     }
  810.     return dict_items((dictobject *)mp, (PyObject *)NULL);
  811. }
  812.  
  813. #define NEWCMP
  814.  
  815. #ifdef NEWCMP
  816.  
  817. /* Subroutine which returns the smallest key in a for which b's value
  818.    is different or absent.  The value is returned too, through the
  819.    pval argument.  No reference counts are incremented. */
  820.  
  821. static PyObject *
  822. characterize(a, b, pval)
  823.     dictobject *a;
  824.     dictobject *b;
  825.     PyObject **pval;
  826. {
  827.     PyObject *diff = NULL;
  828.     int i;
  829.  
  830.     *pval = NULL;
  831.     for (i = 0; i < a->ma_size; i++) {
  832.         if (a->ma_table[i].me_value != NULL) {
  833.             PyObject *key = a->ma_table[i].me_key;
  834.             PyObject *aval, *bval;
  835.             /* XXX What if PyObject_Compare raises an exception? */
  836.             if (diff != NULL && PyObject_Compare(key, diff) > 0)
  837.                 continue;
  838.             aval = a->ma_table[i].me_value;
  839.             bval = PyDict_GetItem((PyObject *)b, key);
  840.             /* XXX What if PyObject_Compare raises an exception? */
  841.             if (bval == NULL || PyObject_Compare(aval, bval) != 0)
  842.             {
  843.                 diff = key;
  844.                 *pval = aval;
  845.             }
  846.         }
  847.     }
  848.     return diff;
  849. }
  850.  
  851. static int
  852. dict_compare(a, b)
  853.     dictobject *a, *b;
  854. {
  855.     PyObject *adiff, *bdiff, *aval, *bval;
  856.     int res;
  857.  
  858.     /* Compare lengths first */
  859.     if (a->ma_used < b->ma_used)
  860.         return -1;    /* a is shorter */
  861.     else if (a->ma_used > b->ma_used)
  862.         return 1;    /* b is shorter */
  863.     /* Same length -- check all keys */
  864.     adiff = characterize(a, b, &aval);
  865.     if (PyErr_Occurred())
  866.         return -1;
  867.     if (adiff == NULL)
  868.         return 0;    /* a is a subset with the same length */
  869.     bdiff = characterize(b, a, &bval);
  870.     if (PyErr_Occurred())
  871.         return -1;
  872.     /* bdiff == NULL would be impossible now */
  873.     res = PyObject_Compare(adiff, bdiff);
  874.     if (res == 0)
  875.         res = PyObject_Compare(aval, bval);
  876.     return res;
  877. }
  878.  
  879. #else /* !NEWCMP */
  880.  
  881. static int
  882. dict_compare(a, b)
  883.     dictobject *a, *b;
  884. {
  885.     PyObject *akeys, *bkeys;
  886.     int i, n, res;
  887.     if (a == b)
  888.         return 0;
  889.     if (a->ma_used == 0) {
  890.         if (b->ma_used != 0)
  891.             return -1;
  892.         else
  893.             return 0;
  894.     }
  895.     else {
  896.         if (b->ma_used == 0)
  897.             return 1;
  898.     }
  899.     akeys = dict_keys(a, (PyObject *)NULL);
  900.     bkeys = dict_keys(b, (PyObject *)NULL);
  901.     if (akeys == NULL || bkeys == NULL) {
  902.         /* Oops, out of memory -- what to do? */
  903.         /* For now, sort on address! */
  904.         Py_XDECREF(akeys);
  905.         Py_XDECREF(bkeys);
  906.         if (a < b)
  907.             return -1;
  908.         else
  909.             return 1;
  910.     }
  911.     PyList_Sort(akeys);
  912.     PyList_Sort(bkeys);
  913.     n = a->ma_used < b->ma_used ? a->ma_used : b->ma_used; /* smallest */
  914.     res = 0;
  915.     for (i = 0; i < n; i++) {
  916.         PyObject *akey, *bkey, *aval, *bval;
  917.         long ahash, bhash;
  918.         akey = PyList_GetItem(akeys, i);
  919.         bkey = PyList_GetItem(bkeys, i);
  920.         res = PyObject_Compare(akey, bkey);
  921.         if (res != 0)
  922.             break;
  923. #ifdef CACHE_HASH
  924.         if (!PyString_Check(akey) ||
  925.             (ahash = ((PyStringObject *) akey)->ob_shash) == -1)
  926. #endif
  927.         {
  928.             ahash = PyObject_Hash(akey);
  929.             if (ahash == -1)
  930.                 PyErr_Clear(); /* Don't want errors here */
  931.         }
  932. #ifdef CACHE_HASH
  933.         if (!PyString_Check(bkey) ||
  934.             (bhash = ((PyStringObject *) bkey)->ob_shash) == -1)
  935. #endif
  936.         {
  937.             bhash = PyObject_Hash(bkey);
  938.             if (bhash == -1)
  939.                 PyErr_Clear(); /* Don't want errors here */
  940.         }
  941.         aval = lookdict(a, akey, ahash) -> me_value;
  942.         bval = lookdict(b, bkey, bhash) -> me_value;
  943.         res = PyObject_Compare(aval, bval);
  944.         if (res != 0)
  945.             break;
  946.     }
  947.     if (res == 0) {
  948.         if (a->ma_used < b->ma_used)
  949.             res = -1;
  950.         else if (a->ma_used > b->ma_used)
  951.             res = 1;
  952.     }
  953.     Py_DECREF(akeys);
  954.     Py_DECREF(bkeys);
  955.     return res;
  956. }
  957.  
  958. #endif /* !NEWCMP */
  959.  
  960. static PyObject *
  961. dict_has_key(mp, args)
  962.     register dictobject *mp;
  963.     PyObject *args;
  964. {
  965.     PyObject *key;
  966.     long hash;
  967.     register long ok;
  968.     if (!PyArg_Parse(args, "O", &key))
  969.         return NULL;
  970. #ifdef CACHE_HASH
  971.     if (!PyString_Check(key) ||
  972.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  973. #endif
  974.     {
  975.         hash = PyObject_Hash(key);
  976.         if (hash == -1)
  977.             return NULL;
  978.     }
  979.     ok = mp->ma_size != 0 && lookdict(mp, key, hash)->me_value != NULL;
  980.     return PyInt_FromLong(ok);
  981. }
  982.  
  983. static PyObject *
  984. dict_get(mp, args)
  985.     register dictobject *mp;
  986.     PyObject *args;
  987. {
  988.     PyObject *key;
  989.     PyObject *failobj = Py_None;
  990.     PyObject *val = NULL;
  991.     long hash;
  992.  
  993.     if (!PyArg_ParseTuple(args, "O|O", &key, &failobj))
  994.         return NULL;
  995.     if (mp->ma_table == NULL)
  996.         goto finally;
  997.  
  998. #ifdef CACHE_HASH
  999.     if (!PyString_Check(key) ||
  1000.         (hash = ((PyStringObject *) key)->ob_shash) == -1)
  1001. #endif
  1002.     {
  1003.         hash = PyObject_Hash(key);
  1004.         if (hash == -1)
  1005.             return NULL;
  1006.     }
  1007.     val = lookdict(mp, key, hash)->me_value;
  1008.  
  1009.   finally:
  1010.     if (val == NULL)
  1011.         val = failobj;
  1012.     Py_INCREF(val);
  1013.     return val;
  1014. }
  1015.  
  1016.  
  1017. static PyObject *
  1018. dict_clear(mp, args)
  1019.     register dictobject *mp;
  1020.     PyObject *args;
  1021. {
  1022.     if (!PyArg_NoArgs(args))
  1023.         return NULL;
  1024.     PyDict_Clear((PyObject *)mp);
  1025.     Py_INCREF(Py_None);
  1026.     return Py_None;
  1027. }
  1028.  
  1029. static PyMethodDef mapp_methods[] = {
  1030.     {"has_key",    (PyCFunction)dict_has_key},
  1031.     {"keys",    (PyCFunction)dict_keys},
  1032.     {"items",    (PyCFunction)dict_items},
  1033.     {"values",    (PyCFunction)dict_values},
  1034.     {"update",    (PyCFunction)dict_update},
  1035.     {"clear",    (PyCFunction)dict_clear},
  1036.     {"copy",    (PyCFunction)dict_copy},
  1037.     {"get",         (PyCFunction)dict_get, 1},
  1038.     {NULL,        NULL}        /* sentinel */
  1039. };
  1040.  
  1041. static PyObject *
  1042. dict_getattr(mp, name)
  1043.     dictobject *mp;
  1044.     char *name;
  1045. {
  1046.     return Py_FindMethod(mapp_methods, (PyObject *)mp, name);
  1047. }
  1048.  
  1049. PyTypeObject PyDict_Type = {
  1050.     PyObject_HEAD_INIT(&PyType_Type)
  1051.     0,
  1052.     "dictionary",
  1053.     sizeof(dictobject),
  1054.     0,
  1055.     (destructor)dict_dealloc, /*tp_dealloc*/
  1056.     (printfunc)dict_print, /*tp_print*/
  1057.     (getattrfunc)dict_getattr, /*tp_getattr*/
  1058.     0,            /*tp_setattr*/
  1059.     (cmpfunc)dict_compare, /*tp_compare*/
  1060.     (reprfunc)dict_repr, /*tp_repr*/
  1061.     0,            /*tp_as_number*/
  1062.     0,            /*tp_as_sequence*/
  1063.     &dict_as_mapping,    /*tp_as_mapping*/
  1064. };
  1065.  
  1066. /* For backward compatibility with old dictionary interface */
  1067.  
  1068. PyObject *
  1069. PyDict_GetItemString(v, key)
  1070.     PyObject *v;
  1071.     char *key;
  1072. {
  1073.     PyObject *kv, *rv;
  1074.     kv = PyString_FromString(key);
  1075.     if (kv == NULL)
  1076.         return NULL;
  1077.     rv = PyDict_GetItem(v, kv);
  1078.     Py_DECREF(kv);
  1079.     return rv;
  1080. }
  1081.  
  1082. int
  1083. PyDict_SetItemString(v, key, item)
  1084.     PyObject *v;
  1085.     char *key;
  1086.     PyObject *item;
  1087. {
  1088.     PyObject *kv;
  1089.     int err;
  1090.     kv = PyString_FromString(key);
  1091.     if (kv == NULL)
  1092.         return -1;
  1093.     PyString_InternInPlace(&kv); /* XXX Should we really? */
  1094.     err = PyDict_SetItem(v, kv, item);
  1095.     Py_DECREF(kv);
  1096.     return err;
  1097. }
  1098.  
  1099. int
  1100. PyDict_DelItemString(v, key)
  1101.     PyObject *v;
  1102.     char *key;
  1103. {
  1104.     PyObject *kv;
  1105.     int err;
  1106.     kv = PyString_FromString(key);
  1107.     if (kv == NULL)
  1108.         return -1;
  1109.     err = PyDict_DelItem(v, kv);
  1110.     Py_DECREF(kv);
  1111.     return err;
  1112. }
  1113.